"""
考试系统 - Django Admin 配置
管理考试相关的后台界面
"""
from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Count, Avg, Sum
from django.urls import reverse
from django.utils.safestring import mark_safe

from .models import (
    Examination, ExaminationQuestion, ExaminationSession,
    ExaminationAnswer, ExaminationTemplate, ExamStatistics
)


class ExaminationQuestionInline(admin.TabularInline):
    """考试题目内联"""
    model = ExaminationQuestion
    extra = 0
    readonly_fields = ['effective_score']
    fields = [
        'question', 'question_order', 'custom_score', 'effective_score', 'is_required'
    ]

    def effective_score(self, obj):
        """有效分数"""
        return obj.effective_score
    effective_score.short_description = '有效分数'

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """外键字段过滤"""
        if db_field.name == 'question':
            kwargs['queryset'] = db_field.remote_field.model.objects.filter(
                status='active'
            ).select_related('creator').order_by('-created_at')
        return super().formfield_for_foreignkey(db_field, request, **kwargs)


@admin.register(Examination)
class ExaminationAdmin(admin.ModelAdmin):
    """考试管理"""
    list_display = [
        'title', 'exam_type', 'status', 'start_time', 'end_time',
        'duration', 'question_bank_name', 'participant_count',
        'is_active', 'creator', 'created_at'
    ]
    list_filter = [
        'exam_type', 'status', 'question_bank',
        'creator', 'start_time', 'created_at'
    ]
    search_fields = ['title', 'description', 'creator__username', 'creator__real_name']
    readonly_fields = [
        'id', 'participant_count', 'is_active', 'is_finished',
        'created_at', 'updated_at'
    ]
    inlines = [ExaminationQuestionInline]
    filter_horizontal = ['supervisors']

    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description', 'exam_type', 'status')
        }),
        ('时间设置', {
            'fields': ('start_time', 'end_time', 'duration', 'allow_late_join')
        }),
        ('考试设置', {
            'fields': ('auto_submit', 'show_score', 'show_answer', 'allow_retake')
        }),
        ('题目配置', {
            'fields': ('question_mode', 'question_bank', 'total_score', 'pass_score')
        }),
        ('人员配置', {
            'fields': ('creator', 'supervisors')
        }),
        ('统计信息', {
            'fields': ('participant_count', 'is_active', 'is_finished'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def question_bank_name(self, obj):
        """获取题库名称"""
        return obj.question_bank.name if obj.question_bank else '-'
    question_bank_name.short_description = '题库'

    def participant_count(self, obj):
        """获取参与人数"""
        return obj.participant_count
    participant_count.short_description = '参与人数'

    def is_active(self, obj):
        """获取活动状态"""
        if obj.is_active:
            return format_html('<span style="color: green;">进行中</span>')
        return format_html('<span style="color: red;">未开始/已结束</span>')
    is_active.short_description = '状态'

    def is_finished(self, obj):
        """获取完成状态"""
        if obj.is_finished:
            return format_html('<span style="color: red;">已结束</span>')
        return format_html('<span style="color: green;">未结束</span>')
    is_finished.short_description = '完成状态'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'question_bank', 'creator', 'supervisors'
        ).prefetch_related('questions', 'exam_sessions')

    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑时
            return self.readonly_fields + ['creator']
        return self.readonly_fields

    def change_view(self, request, object_id=None, form_url='', extra_context=None):
        """自定义视图"""
        extra_context = extra_context or {}
        if object_id:
            extra_context['show_statistics'] = True
        return super().change_view(request, object_id, form_url, extra_context)


@admin.register(ExaminationSession)
class ExaminationSessionAdmin(admin.ModelAdmin):
    """考试会话管理"""
    list_display = [
        'user_info', 'examination_title', 'status', 'started_at',
        'finished_at', 'time_spent_formatted', 'total_score',
        'passed', 'ip_address', 'cheating_detected'
    ]
    list_filter = [
        'status', 'passed', 'cheating_detected',
        'started_at', 'finished_at', 'examination'
    ]
    search_fields = [
        'user__username', 'user__real_name',
        'examination__title'
    ]
    readonly_fields = [
        'id', 'user', 'examination', 'started_at', 'finished_at',
        'time_spent', 'total_score', 'objective_score',
        'subjective_score', 'passed', 'ip_address', 'user_agent',
        'cheating_detected'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'examination', 'status')
        }),
        ('时间信息', {
            'fields': ('started_at', 'finished_at', 'time_spent')
        }),
        ('成绩信息', {
            'fields': (
                'total_score', 'objective_score', 'subjective_score', 'passed'
            )
        }),
        ('监控信息', {
            'fields': ('ip_address', 'user_agent', 'cheating_detected', 'cheating_notes')
        })
    )

    def user_info(self, obj):
        """获取用户信息"""
        return f"{obj.user.real_name} ({obj.user.username})"
    user_info.short_description = '用户'

    def examination_title(self, obj):
        """获取考试标题"""
        return obj.examination.title
    examination_title.short_description = '考试'

    def time_spent_formatted(self, obj):
        """格式化显示用时"""
        if not obj.time_spent:
            return "-"

        hours = obj.time_spent // 3600
        minutes = (obj.time_spent % 3600) // 60
        seconds = obj.time_spent % 60

        if hours > 0:
            return f"{hours}h {minutes}m {seconds}s"
        elif minutes > 0:
            return f"{minutes}m {seconds}s"
        else:
            return f"{seconds}s"
    time_spent_formatted.short_description = '用时'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'user', 'examination'
        ).prefetch_related('exam_answers')

    def get_actions(self, request):
        """自定义批量操作"""
        actions = super().get_actions(request)

        if request.user.is_superuser:
            # 添加重新计算分数操作
            actions['recalculate_scores'] = 'recalculate_scores'

        return actions

    def recalculate_scores(self, request, queryset):
        """重新计算分数"""
        count = 0
        for session in queryset:
            try:
                session.calculate_score()
                session.save(update_fields=['total_score', 'passed', 'objective_score', 'subjective_score'])
                count += 1
            except Exception as e:
                self.message_user(request, f"会话 {session.id} 计算失败: {e}", level='error')

        self.message_user(request, f"重新计算了 {count} 个会话的分数")

    recalculate_scores.short_description = "重新计算分数"


class ExaminationAnswerInline(admin.TabularInline):
    """考试答案内联"""
    model = ExaminationAnswer
    extra = 0
    readonly_fields = ['question_info', 'question_type', 'effective_score']
    fields = [
        'question_info', 'question_type', 'answer', 'text_answer',
        'score', 'is_correct', 'status', 'time_spent', 'view_count'
    ]

    def question_info(self, obj):
        """获取题目信息"""
        return f"{obj.exam_question.question.title[:30]}..."
    question_info.short_description = '题目'

    def question_type(self, obj):
        """获取题目类型"""
        return obj.exam_question.question.get_type_display()
    question_type.short_description = '类型'

    def effective_score(self, obj):
        """获取有效分数"""
        return obj.exam_question.effective_score
    effective_score.short_description = '分数'


@admin.register(ExaminationAnswer)
class ExaminationAnswerAdmin(admin.ModelAdmin):
    """考试答案管理"""
    list_display = [
        'session_info', 'question_info', 'question_type',
        'score', 'is_correct', 'status', 'time_spent', 'view_count'
    ]
    list_filter = [
        'status', 'is_correct', 'exam_question__question__type',
        'answered_at'
    ]
    search_fields = [
        'exam_session__user__username', 'exam_session__user__real_name',
        'exam_question__question__title'
    ]
    readonly_fields = [
        'id', 'exam_session', 'exam_question', 'effective_score'
    ]

    def session_info(self, obj):
        """获取会话信息"""
        return f"{obj.exam_session.user.real_name}"
    session_info.short_description = '会话'

    def question_info(self, obj):
        """获取题目信息"""
        return f"{obj.exam_question.question.title[:30]}..."
    question_info.short_description = '题目'

    def question_type(self, obj):
        """获取题目类型"""
        return obj.exam_question.question.get_type_display()
    question_type.short_description = '类型'

    def effective_score(self, obj):
        """获取有效分数"""
        return obj.exam_question.effective_score
    effective_score.short_description = '分数'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'exam_session__user', 'exam_question__question'
        ).prefetch_related('exam_question')


@admin.register(ExaminationTemplate)
class ExaminationTemplateAdmin(admin.ModelAdmin):
    """考试模板管理"""
    list_display = [
        'name', 'exam_type', 'duration', 'total_score',
        'pass_percentage', 'usage_count', 'creator', 'created_at'
    ]
    list_filter = [
        'exam_type', 'creator', 'created_at'
    ]
    search_fields = [
        'name', 'description', 'creator__username', 'creator__real_name'
    ]
    readonly_fields = [
        'id', 'usage_count', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'exam_type')
        }),
        ('题目配置', {
            'fields': ('duration', 'question_mode')
        }),
        ('模板配置', {
            'fields': ('question_config',)
        }),
        ('分数配置', {
            'fields': ('total_score', 'pass_percentage')
        }),
        ('考试设置', {
            'fields': ('settings',)
        }),
        ('统计信息', {
            'fields': ('usage_count', 'created_at', 'updated_at')
        })
    )

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('creator')


@admin.register(ExamStatistics)
class ExamStatisticsAdmin(admin.ModelAdmin):
    """考试统计管理"""
    list_display = [
        'examination_title', 'total_participants', 'completed_count',
        'passed_count', 'average_score', 'pass_rate', 'completion_rate'
    ]
    list_filter = [
        'examination__exam_type', 'updated_at'
    ]
    search_fields = [
        'examination__title', 'examination__creator__username'
    ]
    readonly_fields = [
        'examination', 'total_participants', 'completed_count',
        'passed_count', 'average_score', 'highest_score', 'lowest_score',
        'score_distribution', 'question_analysis', 'time_analysis',
        'updated_at'
    ]

    def examination_title(self, obj):
        """获取考试标题"""
        return obj.examination.title
    examination_title.short_description = '考试'

    def pass_rate(self, obj):
        """获取及格率"""
        if obj.completed_count == 0:
            return "0%"
        rate = (obj.passed_count / obj.completed_count) * 100
        return f"{rate:.1f}%"
    pass_rate.short_description = '及格率'

    def completion_rate(self, obj):
        """获取完成率"""
        if obj.total_participants == 0:
            return "0%"
        rate = (obj.completed_count / obj.total_participants) * 100
        return f"{rate:.1f}%"
    completion_rate.short_description = '完成率'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('examination')

    def change_view(self, request, object_id=None, form_url='', extra_context=None):
        """自定义视图"""
        extra_context = extra_context or {}
        if object_id:
            extra_context['show_detail_analysis'] = True
        return super().change_view(request, object_id, form_url, extra_context)

    def get_actions(self, request):
        """自定义批量操作"""
        actions = super().get_actions(request)

        # 添加更新统计操作
        actions['update_statistics'] = 'update_statistics'

        return actions

    def update_statistics(self, request, queryset):
        """更新统计数据"""
        count = 0
        for stats in queryset:
            try:
                stats.update_statistics()
                count += 1
            except Exception as e:
                self.message_user(request, f"统计 {stats.id} 更新失败: {e}", level='error')

        self.message_user(request, f"更新了 {count} 个统计数据")

    update_statistics.short_description = "更新统计"


# 自定义Admin站点标题
admin.site.site_header = 'AI-SOES 智能在线考试系统'
admin.site.site_title = 'AI-SOES 考试管理'
admin.site.index_title = '智能在线考试系统 - 考试管理后台'